package com.vegetable.modules.service.bank.convert;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.vegetable.modules.entity.finance.Transactions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 农行流水标准化字段输出
 */
@Slf4j
public class ABCConverter extends BankGenerator {

	private static final String bankMark = "ABC";

	public List<Transactions> convert(MultipartFile file) throws Exception {
		List<com.vegetable.modules.entity.finance.Transactions> result  = convertA(file);
		if(CollectionUtil.isEmpty(result)){
			result = convertB(file);
		}
		return result;
	}

	public List<Transactions> convertA(MultipartFile file) throws Exception {
		List<Transactions> result = new ArrayList<>();
		try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
			Sheet sheet = workbook.getSheetAt(0);
			int lastRow = sheet.getLastRowNum();
			// 首先使用方案A
			for(int i = 3; i < lastRow; i++){
				Row currentR = sheet.getRow(i);
				try {
					Transactions thisT = getTransactions(currentR);
					result.add(thisT);
				} catch (Exception e) {
					log.error("转换流水异常->{}", currentR);
				}
			}
		}catch (Exception e){
			log.error("转换建行流水发生异常--->", e);
			return null;
		}
		return result;
	}

	public List<Transactions> convertB(MultipartFile file) throws Exception {
		List<Transactions> result = new ArrayList<>();
		try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
			Sheet sheet = workbook.getSheetAt(0);
			int lastRow = sheet.getLastRowNum();
			// 如果没结果，则使用方案B
			for(int i = 3; i <= lastRow; i++){
				Row currentR = sheet.getRow(i);
				Transactions thisT = getTransactionsB(currentR);
				result.add(thisT);
			}
		}catch (Exception e){
			log.error("转换建行流水发生异常--->", e);
			return null;
		}
		return result;
	}

	@NotNull
	private Transactions getTransactions(Row currentR) throws Exception {
		Transactions thisT = new Transactions();
		thisT.setTradingType(getDoubleCell(currentR, 2) > 0 ? "EXPENSE" : "INCOME");
		Date legacyDate = DateUtil.parse(getStringCell(currentR, 0), "yyyy-MM-dd HH:mm:ss");
		thisT.setTradingTime(legacyDate);
		thisT.setTradingAmount("INCOME".equals(thisT.getTradingType()) ? getBCCell(currentR, 1) : getBCCell(currentR, 2));
		thisT.setBalanceAmount(getBCCell(currentR, 3));
		thisT.setBankName(getStringCell(currentR, 6));
		thisT.setBankNo(getStringCell(currentR, 4));
		thisT.setCounterparty(getStringCell(currentR, 5));
		thisT.setTradingDescription(getStringCell(currentR, 7));
		thisT.setRemark("");
		thisT.setChannel(bankMark);
		thisT.setTradingNo(Transactions.generateUniqueFlowId(thisT));
		return thisT;
	}

	@NotNull
	private Transactions getTransactionsB(Row currentR) throws Exception {
		Transactions thisT = new Transactions();
		try {
			String tradingAmount = getStringCell(currentR, 2);
			thisT.setTradingType(tradingAmount.startsWith("-") ? "EXPENSE" : "INCOME");
			// 1. 解析日期部分 (yyyyMMdd)
			LocalDate date = LocalDate.parse(currentR.getCell(0).getStringCellValue(), DateTimeFormatter.ISO_DATE);
			// 2. 解析时间部分 (HH:mm:ss)
			LocalTime time = LocalTime.parse(currentR.getCell(1).getStringCellValue());
			LocalDateTime dateTime = LocalDateTime.of(date, time);
			Date legacyDate = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
			thisT.setTradingTime(legacyDate);
			thisT.setTradingAmount(getBCCell(currentR, 2));
			thisT.setBalanceAmount(getBCCell(currentR, 3));
			thisT.setBankName(getStringCell(currentR, 6));
			thisT.setBankNo(getStringCell(currentR, 5));
			thisT.setCounterparty(getStringCell(currentR, 4));
			thisT.setTradingDescription(getStringCell(currentR, 9));
			thisT.setRemark(getStringCell(currentR, 10));
			thisT.setChannel(bankMark);
			thisT.setTradingNo(Transactions.generateUniqueFlowId(thisT));
		}catch (Exception e){
			log.info("这行数据有问题{}", currentR.getRowNum());
			e.printStackTrace();
		}
		return thisT;
	}
}
